package com.zzyl.nursing.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.DeviceDataPageReqDto;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.service.IDeviceDataService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 设备数据Service业务层处理
 *
 * @author FuJiaWei
 * @date 2025-06-02
 */
@Service
@Slf4j
public class DeviceDataServiceImpl extends ServiceImpl<DeviceDataMapper, DeviceData> implements IDeviceDataService {
    @Autowired
    private DeviceDataMapper deviceDataMapper;
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 查询设备数据
     *
     * @param id 设备数据主键
     * @return 设备数据
     */
    @Override
    public DeviceData selectDeviceDataById(Long id) {
        return getById(id);
    }

    /**
     * 查询设备数据列表
     *
     * @param deviceDataPageReqDto 设备数据
     * @return 设备数据
     */
    @Override
    public List<DeviceData> selectDeviceDataList(DeviceDataPageReqDto deviceDataPageReqDto) {
        List<DeviceData> list = lambdaQuery()
                .eq(StrUtil.isNotEmpty(deviceDataPageReqDto.getDeviceName()), DeviceData::getDeviceName, deviceDataPageReqDto.getDeviceName())
                .eq(StrUtil.isNotEmpty(deviceDataPageReqDto.getFunctionId()), DeviceData::getFunctionId, deviceDataPageReqDto.getFunctionId())
                .ge(ObjectUtil.isNotEmpty(deviceDataPageReqDto.getStartTime()), DeviceData::getAlarmTime, deviceDataPageReqDto.getStartTime())
                .le(ObjectUtil.isNotEmpty(deviceDataPageReqDto.getEndTime()), DeviceData::getAlarmTime, deviceDataPageReqDto.getEndTime())
                .list();
        return list;
    }

    /**
     * 新增设备数据
     *
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int insertDeviceData(DeviceData deviceData) {
        return save(deviceData) ? 1 : 0;
    }

    /**
     * 修改设备数据
     *
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int updateDeviceData(DeviceData deviceData) {
        return updateById(deviceData) ? 1 : 0;
    }

    /**
     * 批量删除设备数据
     *
     * @param ids 需要删除的设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除设备数据信息
     *
     * @param id 设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 批量保存数据
     *
     * @param iotMsgNotifyData
     */
    @Override
    public void batchInsertDeviceData(IotMsgNotifyData iotMsgNotifyData) {
        //获取header
        IotMsgHeader header = iotMsgNotifyData.getHeader();
        String iotId = header.getDeviceId();
        Device device = deviceMapper.selectOne(new LambdaQueryWrapper<Device>().eq(Device::getIotId, iotId));
        if (device == null) {
            //日志的记录，方便后期查找问题
            log.error("设备不存在，iotId:{}", iotId);
            return;
        }
        //获取body
        List<IotMsgService> services = iotMsgNotifyData.getBody().getServices();
        LocalDateTime alarmTime = getalarmTime(services);
        List<DeviceData> collect = new ArrayList<>();
        for (IotMsgService service : services) {
            Map<String, Object> properties = service.getProperties();
            collect = properties.entrySet().stream().map(e -> {
                DeviceData deviceData = BeanUtil.toBean(device, DeviceData.class);
                deviceData.setId(null);
                deviceData.setFunctionId(e.getKey());
                deviceData.setAccessLocation(device.getRemark());
                deviceData.setDataValue(e.getValue().toString());
                deviceData.setAlarmTime(alarmTime);
                deviceData.setCreateBy(null);
                deviceData.setCreateTime(null);
                deviceData.setUpdateBy(null);
                deviceData.setUpdateTime(null);
                return deviceData;
            }).collect(Collectors.toList());
            saveBatch(collect);
        }
        //存储到redis中deviceDataList
        //hash 结构来进行存储  大key  小key  value
        stringRedisTemplate.opsForHash().put(CacheConstants.IOT_DEVICE_LAST_DATA, iotId, JSONUtil.toJsonStr(collect));
    }

    public LocalDateTime getalarmTime(List<IotMsgService> services) {
        LocalDateTime alarmTime = LocalDateTime.now();
        for (IotMsgService service : services) {
            LocalDateTime parse = LocalDateTimeUtil.parse(service.getEventTime(), "yyyyMMdd'T'HHmmss'Z'");
            //日期时区转换
            alarmTime = parse.atZone(ZoneId.from(ZoneOffset.UTC))
                    .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                    .toLocalDateTime();
        }
        return alarmTime;
    }
}
